<?php
include 'cookie.php';
$user = isset($_COOKIE['enorg']) ? $_COOKIE['enorg'] : 'bozo'; 
// 检查是否存在测试目录，如果存在则使用测试目录
$useTestPath = is_dir($user.'-output/CP');
$tempPath = $useTestPath ? $user.'-output/CP' : ($_COOKIE['enorg'] . '-output/CP');
$excludedFolders = ['BizyAIR', 'OR', 'temp', 'CP', 'GEO']; // 排除的文件夹

// 获取所有类别
$categories = ['根目录'];
if (is_dir($tempPath)) {
    $items = scandir($tempPath);
    foreach ($items as $item) {
        if ($item != '.' && $item != '..' && is_dir($tempPath . '/' . $item) && !in_array($item, $excludedFolders)) {
            $categories[] = $item;
        }
    }
}

// 添加缓存机制
$cacheFile = sys_get_temp_dir() . '/works_cache_' . md5($tempPath) . '.json';
$cacheTime = 300; // 缓存5分钟

// 检查缓存是否存在且未过期
$works = [];
if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTime) {
    // 使用缓存
    $works = json_decode(file_get_contents($cacheFile), true);
} else {
    // 重新扫描并生成数据
    // 获取所有作品
    $works = [];

    if (is_dir($tempPath)) {
        // 处理根目录
        $rootFiles = scandir($tempPath);
        $imageFiles = [];

        // 辅助函数：获取AI生成图的缩略图
        function getAiThumbnails($aiImages, $tempPath) {
            $aiThumbnails = [];
            foreach ($aiImages as $aiImage) {
                $aiThumbPath = pathinfo($aiImage, PATHINFO_FILENAME) . '_thumb.' . pathinfo($aiImage, PATHINFO_EXTENSION);
                $fullAiThumbPath = $tempPath . '/' . $aiThumbPath;
                if (file_exists($fullAiThumbPath)) {
                    $aiThumbnails[] = $fullAiThumbPath;
                } else {
                    $aiThumbnails[] = $tempPath . '/' . $aiImage;
                }
            }
            return $aiThumbnails;
        }
        
        // 分离图片文件，只处理原图（跳过所有包含_thumb的文件）
        $originalFiles = [];
        foreach ($rootFiles as $file) {
            if ($file != '.' && $file != '..') {
                $extension = pathinfo($file, PATHINFO_EXTENSION);
                if (in_array($extension, ['webp', 'jpg', 'png', 'jpeg'])) {
                    // 跳过所有已经是缩略图的文件（包含_thumb的）
                    if (strpos($file, '_thumb') !== false) {
                        continue;
                    }
                    $originalFiles[] = $file;
                }
            }
        }

        // 为每个原图生成对应的数据结构，包含缩略图路径
        $processedImages = [];
        foreach ($originalFiles as $imageFile) {
            $baseName = pathinfo($imageFile, PATHINFO_FILENAME);
            $extension = pathinfo($imageFile, PATHINFO_EXTENSION);

            // 查找对应的缩略图
            $thumbPath = $baseName . '_thumb.' . $extension;
            if (in_array($thumbPath, $rootFiles)) {
                // 有缩略图
                $processedImages[] = [
                    'original' => $imageFile,
                    'thumbnail' => $thumbPath
                ];
            } else {
                // 没有缩略图
                $processedImages[] = [
                    'original' => $imageFile,
                    'thumbnail' => null
                ];
            }
        }

        // 重新构建图片文件列表，只包含原图
        $imageFiles = $originalFiles;
        
        // 处理图片文件，识别没有时间戳的原始图
        foreach ($imageFiles as $imageFile) {

            // 检查是否包含时间戳（简单判断是否包含数字序列）
            $baseName = pathinfo($imageFile, PATHINFO_FILENAME);
            $hasTimestamp = preg_match('/_\d{4,}/', $baseName);

            // 如果不包含时间戳，则认为是原始图
            if (!$hasTimestamp) {
                // 查找对应的AI生成图（同名但带时间戳的图片）
                $aiImages = [];
                foreach ($imageFiles as $aiImage) {
                    if (strpos($aiImage, $baseName) === 0 && $aiImage !== $imageFile) {
                        $aiImages[] = $aiImage;
                    }
                }

                // 获取文件创建时间
                $fileTime = filemtime($tempPath . '/' . $imageFile);
                $createdDate = date('Y-m-d', $fileTime);

                // 查找对应的缩略图
                $thumbnailPath = null;
                foreach ($processedImages as $processed) {
                    if ($processed['original'] === $imageFile && $processed['thumbnail']) {
                        $thumbnailPath = $tempPath . '/' . $processed['thumbnail'];
                        break;
                    }
                }

                $works[] = [
                    'id' => $baseName,
                    'imageName' => $baseName,
                    'category' => '根目录',
                    'thumbnail' => $thumbnailPath ? $thumbnailPath : ($tempPath . '/' . $imageFile), // 有缩略图用缩略图，没有用原图
                    'originalImage' => $tempPath . '/' . $imageFile, // 原图路径
                    'aiThumbnails' => getAiThumbnails($aiImages, $tempPath), // AI生成图的缩略图
                    'aiImages' => $aiImages,
                    'created' => $createdDate,
                    'filePath' => $tempPath . '/' . $imageFile
                ];
            }
        }
        
        // 处理子目录
        foreach ($rootFiles as $item) {
            if ($item != '.' && $item != '..' && is_dir($tempPath . '/' . $item) && !in_array($item, $excludedFolders)) {
                $category = $item;
                $categoryPath = $tempPath . '/' . $category;
                $categoryFiles = scandir($categoryPath);
                $categoryImageFiles = [];
                
                // 分离图片文件
                foreach ($categoryFiles as $file) {
                    if ($file != '.' && $file != '..') {
                        $extension = pathinfo($file, PATHINFO_EXTENSION);
                        if (in_array($extension, ['webp', 'jpg', 'png', 'jpeg'])) {
                            $categoryImageFiles[] = $file;
                        }
                    }
                }
                
                // 分离图片文件，只处理原图（跳过所有包含_thumb的文件）
                $categoryOriginalFiles = [];
                foreach ($categoryFiles as $file) {
                    if ($file != '.' && $file != '..') {
                        $extension = pathinfo($file, PATHINFO_EXTENSION);
                        if (in_array($extension, ['webp', 'jpg', 'png', 'jpeg'])) {
                            // 跳过所有已经是缩略图的文件（包含_thumb的）
                            if (strpos($file, '_thumb') !== false) {
                                continue;
                            }
                            $categoryOriginalFiles[] = $file;
                        }
                    }
                }

                // 为每个原图生成对应的数据结构，包含缩略图路径
                $categoryProcessedImages = [];
                foreach ($categoryOriginalFiles as $imageFile) {
                    $baseName = pathinfo($imageFile, PATHINFO_FILENAME);
                    $extension = pathinfo($imageFile, PATHINFO_EXTENSION);

                    // 查找对应的缩略图
                    $thumbPath = $baseName . '_thumb.' . $extension;
                    if (in_array($thumbPath, $categoryFiles)) {
                        // 有缩略图
                        $categoryProcessedImages[] = [
                            'original' => $imageFile,
                            'thumbnail' => $thumbPath
                        ];
                    } else {
                        // 没有缩略图
                        $categoryProcessedImages[] = [
                            'original' => $imageFile,
                            'thumbnail' => null
                        ];
                    }
                }

                // 重新构建图片文件列表，只包含原图
                $categoryImageFiles = $categoryOriginalFiles;

                foreach ($categoryImageFiles as $imageFile) {

                    // 检查是否包含时间戳
                    $baseName = pathinfo($imageFile, PATHINFO_FILENAME);
                    $hasTimestamp = preg_match('/_\d{4,}/', $baseName);

                    // 如果不包含时间戳，则认为是原始图
                    if (!$hasTimestamp) {
                        // 查找对应的AI生成图（同名但带时间戳的图片）
                        $aiImages = [];
                        foreach ($categoryImageFiles as $aiImage) {
                            if (strpos($aiImage, $baseName) === 0 && $aiImage !== $imageFile) {
                                $aiImages[] = $aiImage;
                            }
                        }

                        // 获取文件创建时间
                        $fileTime = filemtime($categoryPath . '/' . $imageFile);
                        $createdDate = date('Y-m-d', $fileTime);

                        // 查找对应的缩略图
                        $thumbnailPath = null;
                        foreach ($categoryProcessedImages as $processed) {
                            if ($processed['original'] === $imageFile && $processed['thumbnail']) {
                                $thumbnailPath = $categoryPath . '/' . $processed['thumbnail'];
                                break;
                            }
                        }

                        $works[] = [
                            'id' => $baseName,
                            'imageName' => $baseName,
                            'category' => $category,
                            'thumbnail' => $thumbnailPath ? $thumbnailPath : ($categoryPath . '/' . $imageFile), // 有缩略图用缩略图，没有用原图
                            'originalImage' => $categoryPath . '/' . $imageFile, // 原图路径
                            'aiThumbnails' => getAiThumbnails($aiImages, $categoryPath), // AI生成图的缩略图
                            'aiImages' => $aiImages,
                            'created' => $createdDate,
                            'filePath' => $categoryPath . '/' . $imageFile
                        ];
                    }
                }
            }
        }
        
        // 按创建时间排序（最新在前）
        usort($works, function($a, $b) {
            return strtotime($b['created']) - strtotime($a['created']);
        });
        
        // 保存到缓存
        file_put_contents($cacheFile, json_encode($works));
    }
}

?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $current_org['cnorg'] ? $current_org['cnorg'].' - ' : ''; ?> 产品数据库</title>
    <link rel="stylesheet" href="https://cdn.staticfile.net/font-awesome/6.7.1/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.staticfile.net/tailwindcss/2.2.9/tailwind.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;500;600;700&family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
    <script src="https://cdn.staticfile.net/motion.js/0.3.0/motion.min.js"></script>
        <!-- <link rel="stylesheet" media="all" href="styles.css" /> -->
    <style>
        @import "styles.css";
        
        /* 添加新的样式 */
        .tab-container {
            margin-bottom: 1rem;
        }
        
        .tab-button {
            padding: 0.5rem 1rem;
            background: transparent;
            border: 1px solid var(--border-color);
            color: var(--text-color);
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .tab-button.active {
            background: var(--primary-color);
            color: white;
            border-color: var(--primary-color);
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
        
        .image-gallery {
            display: flex;
            overflow-x: auto;
            gap: 1rem;
            padding: 1rem 0;
        }
        
        .image-gallery img {
            width: 120px;
            height: 120px;
            object-fit: cover;
            border-radius: 0.5rem;
            cursor: pointer;
            border: 2px solid transparent;
        }
        
        .image-gallery img.active {
            border-color: var(--primary-color);
        }
        
        .form-group {
            margin-bottom: 1rem;
        }
        
        .form-label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
        }
        
        .form-control {
            width: 100%;
            padding: 0.5rem;
            border: 1px solid var(--border-color);
            border-radius: 0.25rem;
        }
        
        .btn-primary {
            background: var(--primary-color);
            color: white;
            padding: 0.5rem 1rem;
            border: none;
            border-radius: 0.25rem;
            cursor: pointer;
            transition: background 0.3s ease;
        }
        
        .btn-primary:hover {
            background: #4f46e5;
        }
        
        .btn-primary:disabled {
            background: #9ca3af;
            cursor: not-allowed;
        }
        
        .slider-container {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .slider-value {
            min-width: 2rem;
            text-align: center;
        }
        
        /* 轮播样式 */
        .carousel-container {
            position: relative;
            width: 100%;
            height: 500px;
            overflow: hidden;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .carousel-slide {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            transition: opacity 0.5s ease-in-out;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .carousel-slide.active {
            opacity: 1;
        }
        
        .carousel-slide img {
            max-width: 100%;
            max-height: 100%;
            width: auto;
            height: auto;
            object-fit: contain;
        }
        
        .carousel-controls {
            position: absolute;
            top: 50%;
            left: 0;
            right: 0;
            display: flex;
            justify-content: space-between;
            z-index: 10;
            transform: translateY(-50%);
            pointer-events: none;
        }
        
        .carousel-btn {
            background: rgba(255, 255, 255, 0.3);
            color: #333;
            border: none;
            padding: 0.75rem;
            cursor: pointer;
            transition: all 0.3s ease;
            border-radius: 50%;
            margin: 0 1rem;
            pointer-events: auto;
        }
        
        .carousel-btn:hover {
            background: rgba(255, 255, 255, 0.8);
            transform: scale(1.1);
        }
        
        .carousel-indicators {
            position: absolute;
            bottom: 1rem;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            gap: 0.5rem;
        }
        
        .indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.5);
            cursor: pointer;
            transition: background 0.3s ease;
        }
        
        .indicator.active {
            background: white;
        }
        
        /* 懒加载样式 */
        img.lazy {
            opacity: 0;
            transition: opacity 0.3s;
        }
        
        img.lazy.loaded {
            opacity: 1;
        }
        
        /* 骨架屏样式 */
        .skeleton {
            background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
            background-size: 200% 100%;
            animation: loading 1.5s infinite;
            border-radius: 0.5rem;
        }
        
        /* API响应信息样式 */
        .api-response pre {
            max-height: 200px;
            overflow-y: auto;
            white-space: pre-wrap;
            word-break: break-all;
            font-size: 0.6rem;
            background: #f8f9fa;
            padding: 1rem;
            border-radius: 0.5rem;
            border: 1px solid #e9ecef;
            color: #6b7280; /* 灰色文字 */
        }

        @keyframes loading {
            0% {
                background-position: 200% 0;
            }
            100% {
                background-position: -200% 0;
            }
        }
    </style>
</head>
<body class="font-sans antialiased transition-colors duration-300 light-mode">
    <!-- 导航栏 -->
    <nav class="navbar sticky top-0 z-50">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center h-16">
                <div class="flex items-center">
                    <div class="flex-shrink-0 flex items-center">
                        <div class="w-10 h-10 bg-gradient-to-r from-indigo-500 to-purple-600 rounded-xl flex items-center justify-center">
                            <i class="fas fa-robot text-white text-lg"></i>
                        </div>
                        <h1 class="text-xl font-bold text-gray-900 dark:text-white ml-3"><?php echo $current_org['cnorg'] ? $current_org['cnorg'].' - ' : ''; ?> 产品数据库</h1>
                    </div>
                </div>
                <div class="flex items-center space-x-4">
                    <!-- 类别筛选 -->
                    <div id="category-filter" class="hidden md:block">
                        <div class="ml-4 flex items-center space-x-3" id="category-buttons">
                            <?php
                            // 输出类别按钮
                            echo '<button class="category-btn active" data-category="根目录">根目录</button>';
                            
                            foreach ($categories as $category) {
                                if ($category !== '根目录' && !in_array($category, $excludedFolders)) {
                                    echo '<button class="category-btn" data-category="' . htmlspecialchars($category) . '">' . htmlspecialchars($category) . '</button>';
                                }
                            }
                            ?>
                        </div>
                    </div>
                    
                    <!-- 模式切换 -->
                    <button id="theme-toggle" class="theme-toggle">
                        <i class="fas fa-moon"></i>
                    </button>
                    <!-- 返回图像反推按钮 -->
                    <button id="back-to-wd" class="hidden md:flex items-center px-4 py-2 rounded-lg text-sm font-medium text-white bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-all duration-300 shadow-lg" onclick="window.location.href='BizyAIR/index.php?login=<?php echo $login_org; ?>&id=37316'">
                        <i class="fas fa-arrow-left mr-2"></i>
                        图像重绘
                    </button>
                    
                    <!-- 缩略图压缩按钮 -->
                    <button id="thumbnail-compress-btn" class="hidden md:flex items-center px-4 py-2 rounded-lg text-sm font-medium text-white bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-700 hover:to-emerald-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition-all duration-300 shadow-lg" onclick="compressThumbnails()">
                        <i class="fas fa-compress mr-2"></i>
                        缩略图压缩
                    </button>

                    <!-- 移动端菜单按钮 -->
                    <button class="md:hidden p-2 rounded-lg text-gray-500 hover:text-gray-900 hover:bg-gray-100 dark:text-gray-400 dark:hover:text-white dark:hover:bg-gray-700" id="mobile-menu-button">
                        <i class="fas fa-bars"></i>
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 移动端菜单 -->
        <div class="md:hidden hidden" id="mobile-menu">
            <div class="px-4 pt-4 pb-4 space-y-2 sm:px-6" id="mobile-category-buttons">
                <?php
                echo '<button class="w-full text-left px-4 py-3 rounded-lg bg-indigo-100 dark:bg-indigo-900 text-indigo-800 dark:text-indigo-200 category-btn active" data-category="根目录">根目录</button>';
                
                foreach ($categories as $category) {
                    if ($category !== '根目录' && !in_array($category, $excludedFolders)) {
                        echo '<button class="w-full text-left px-4 py-3 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 category-btn" data-category="' . htmlspecialchars($category) . '">' . htmlspecialchars($category) . '</button>';
                    }
                }
                ?>
            </div>
        </div>
    </nav>

    <!-- 主要内容 -->
    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
        <!-- 标题 -->
        <div class="mb-10 text-center">
            <h2 class="text-4xl font-bold text-gray-900 dark:text-white mb-4"> 产品数据展示</h2>
            <p class="text-xl text-gray-600 dark:text-gray-300 max-w-3xl mx-auto">产品数据整理，按照要求重绘</p>
        </div>
        
        <!-- 作品网格 -->
        <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-4 gap-6" id="gallery-grid">
            <?php
            // 输出作品卡片 - 使用缓存机制版本的数据
            $displayedWorks = array_slice($works, 0, 8);

            if (count($displayedWorks) > 0) {
                foreach ($displayedWorks as $work) {
                    echo '<div class="card group animate-fade-in-up">';
                    echo '<div class="thumbnail-container">';
                    echo '<img src="' . htmlspecialchars($work['thumbnail']) . '" alt="' . htmlspecialchars($work['imageName']) . '" class="thumbnail">';
                    echo '<div class="category-tag">' . htmlspecialchars($work['category']) . '</div>';
                    echo '</div>';
                    echo '<div class="card-content">';
                    echo '<h3 class="card-title">' . htmlspecialchars($work['imageName']) . '</h3>';
                    echo '<div class="card-meta">';
                    echo '<span class="date">' . htmlspecialchars($work['created']) . '</span>';
                    echo '<span class="models">';
                    echo '<i class="fas fa-image text-xs mr-1"></i>';
                    echo '产品图';
                    echo '</span>';
                    echo '</div>';
                    echo '</div>';
                    echo '</div>';
                }
            } else {
                echo '<div class="col-span-full text-center py-16">';
                echo '<div class="inline-block p-6 bg-gray-100 dark:bg-gray-800 rounded-2xl mb-6">';
                echo '<i class="fas fa-image text-6xl text-gray-400"></i>';
                echo '</div>';
                echo '<h3 class="text-2xl font-bold text-gray-700 dark:text-gray-300 mb-2">暂无产品图</h3>';
                echo '<p class="text-gray-500 dark:text-gray-400">请上传产品图文件</p>';
                echo '</div>';
            }
            ?>
        </div>
        
        <!-- 加载更多按钮 -->
        <div class="mt-12 text-center">
            <?php if (count($works) > 8): ?>
            <button id="load-more" class="load-more-btn">
                <i class="fas fa-spinner fa-spin mr-2 loading-animation hidden"></i>
                <span>加载更多产品图</span>
            </button>
            <?php endif; ?>
        </div>
        
        <!-- 滚动指示器 -->
        <div class="scroll-indicator hidden" id="scroll-indicator">
            <i class="fas fa-arrow-down"></i>
        </div>
    </main>

    <!-- 作品详情模态框 -->
    <div class="fixed inset-0 bg-black bg-opacity-60 z-50 flex items-center justify-center p-4 hidden" id="modal">
        <div class="bg-white dark:bg-gray-800 rounded-2xl max-w-5xl w-full max-h-screen overflow-y-auto animate-fade-in-up">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="modal-title" id="modal-title">产品图详情</h3>
                    <button class="modal-close" id="close-modal">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="modal-grid">
                    <!-- 图片显示区域 -->
                    <div class="modal-image-container">
                        <!-- 标签页 -->
                        <div class="tab-container" style="display: flex; gap: 0.5rem;">
                            <button class="tab-button active" data-tab="original">原始图</button>
                            <button class="tab-button" data-tab="ai">AI生成图</button>
                        </div>
                        
                        <!-- 原始图内容 -->
                        <div class="tab-content m-10 active" id="original-tab">
                            <img src="" alt="原始图" class="modal-image" id="original-image">
                        </div>
                        
                        <!-- AI生成图内容 -->
                        <div class="tab-content" id="ai-tab">
                            <!-- 轮播容器 -->
                            <div class="carousel-container" id="ai-carousel">
                                <!-- 轮播项将动态填充 -->
                                <div class="carousel-controls">
                                    <button class="carousel-btn" id="prev-btn"><i class="fas fa-chevron-left"></i></button>
                                    <button class="carousel-btn" id="next-btn"><i class="fas fa-chevron-right"></i></button>
                                </div>
                                <div class="carousel-indicators" id="carousel-indicators">
                                    <!-- 指示器将动态填充 -->
                                </div>
                            </div>
                            <!-- 下载按钮 -->
                            <div class="mt-4 mb-4 text-center">
                                <button class="btn-primary" id="download-ai-image">
                                    <i class="fas fa-download mr-2"></i>
                                    下载图片
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 图片编辑区域 -->
                    <div>
                        <div class="info-section hidden">
                            <h4 class="info-title">图片信息</h4>
                            <div class="info-grid">
                                <div class="info-item">
                                    <span class="info-label">图片名称:</span>
                                    <span class="info-value" id="modal-image-name">-</span>
                                </div>
                                <div class="info-item">
                                    <span class="info-label">分类:</span>
                                    <span class="info-value" id="modal-category">-</span>
                                </div>
                                <div class="info-item">
                                    <span class="info-label">创建时间:</span>
                                    <span class="info-value" id="modal-created">-</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="info-section">
                            <div class="hidden">
                            <h4 class="info-title">图片编辑</h4></div>
                            <div class="space-y-4">
                                <!-- 动态提醒区域 -->
                                <div id="edit-alert" class="hidden"></div>
                                
                                <div class="form-group">
                                    <label class="form-label" for="prompt">图片编辑Prompt</label>
                                    <textarea class="form-control" id="prompt" rows="8" placeholder="请输入Prompt">Add a living room scene to the product in the picture, keeping the consistency of the product's material, angle, and texture</textarea>
                                </div>
                                
                                <div class="grid grid-cols-2 gap-4 mb-4">
                                    <div class="form-group">
                                        <label class="form-label" for="batch-size">生成批次数量</label>
                                        <div class="slider-container">
                                            <input type="range" class="form-control range-slider" id="batch-size" min="1" max="4" value="1">
                                            <span class="slider-value" id="batch-size-value">1</span>
                                        </div>
                                    </div>
                                
                                    <div class="form-group">
                                        <label class="form-label" for="resolution">图片尺寸</label>
                                        <select class="form-control" id="resolution">
                                            <?php
                                            // 读取分辨率配置文件
                                            $resolutionFile = 'BizyAIR/resolution.txt';
                                            if (file_exists($resolutionFile)) {
                                                $resolutions = file($resolutionFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
                                                foreach ($resolutions as $resolution) {
                                                    echo '<option value="' . htmlspecialchars($resolution) . '">' . htmlspecialchars($resolution) . '</option>';
                                                }
                                            }
                                            ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <input type="hidden" id="current-image" value="">
                                
                                <div class="text-center">
                                    <button class="btn-primary" id="edit-image-btn">
                                        <i class="fas fa-spinner fa-spin mr-2 hidden" id="edit-loading"></i>
                                        AI立即生成
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <!-- API响应信息 -->
                        <div class="info-section">
                            <div class="hidden">
                            <h4 class="info-title">API响应信息</h4>
                            </div>
                            <div class="api-response" id="api-response">
                                <pre>暂无API响应信息</pre>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 从PHP获取作品数据
        const worksData = <?php echo json_encode($works); ?>;
        let currentCategory = '根目录';
        let displayedCount = 8;
        let isLoading = false;
        let isDarkMode = false;
        let currentSlideIndex = 0;
        let carouselSlides = [];

        // DOM元素
        const galleryGrid = document.getElementById('gallery-grid');
        const loadMoreBtn = document.getElementById('load-more');
        const modal = document.getElementById('modal');
        const closeModalBtn = document.getElementById('close-modal');
        const themeToggle = document.getElementById('theme-toggle');
        const mobileMenuButton = document.getElementById('mobile-menu-button');
        const mobileMenu = document.getElementById('mobile-menu');
        const scrollIndicator = document.getElementById('scroll-indicator');
        const categoryButtons = document.querySelectorAll('.category-btn');

        // 初始化应用
        function initApp() {
            // 默认浅色模式
            document.body.classList.add('light-mode');

            // 绑定事件监听器
            bindEventListeners();

            // 显示滚动指示器
            showScrollIndicator();

            // 为作品卡片添加点击事件
            addCardClickEvents();
        }

        // 为作品卡片添加点击事件
        function addCardClickEvents() {
            document.querySelectorAll('.card').forEach(card => {
                // 为卡片添加数据属性，直接存储work数据
                const cardTitle = card.querySelector('.card-title').textContent;
                const work = worksData.find(w => w.imageName === cardTitle);

                if (work) {
                    card.dataset.work = JSON.stringify(work);

                    card.addEventListener('click', function() {
                        const workData = JSON.parse(this.dataset.work);
                        openModal(workData);
                    });

                    // 为图片也添加点击事件
                    const thumbnail = card.querySelector('.thumbnail');
                    if (thumbnail) {
                        thumbnail.addEventListener('click', function(e) {
                            e.stopPropagation(); // 防止事件冒泡到card
                            const workData = JSON.parse(card.dataset.work);
                            openModal(workData);
                        });
                    }
                }
            });
        }

        // 绑定事件监听器
        function bindEventListeners() {
            // 加载更多按钮
            if (loadMoreBtn) {
                loadMoreBtn.addEventListener('click', loadMoreWorks);
            }
            
            // 关闭模态框
            closeModalBtn.addEventListener('click', closeModal);
            modal.addEventListener('click', function(e) {
                if (e.target === modal) {
                    closeModal();
                }
            });
            
            // 键盘导航
            document.addEventListener('keydown', handleKeyboardNavigation);
            
            // 主题切换
            themeToggle.addEventListener('click', toggleDarkMode);
            
            // 移动端菜单
            mobileMenuButton.addEventListener('click', toggleMobileMenu);

            // 类别筛选
            categoryButtons.forEach(button => {
                button.addEventListener('click', function() {
                    // 移除所有按钮的active类
                    categoryButtons.forEach(btn => btn.classList.remove('active'));
                    // 为当前点击的按钮添加active类
                    this.classList.add('active');
                    // 更新当前类别
                    currentCategory = this.getAttribute('data-category');
                    // 重置显示数量并筛选加载作品
                    resetDisplayedCount();
                    filterAndLoadWorks();
                });
            });

            // 移动端类别筛选
            const mobileCategoryButtons = document.querySelectorAll('#mobile-category-buttons .category-btn');
            mobileCategoryButtons.forEach(button => {
                button.addEventListener('click', function() {
                    // 关闭移动端菜单
                    mobileMenu.classList.add('hidden');

                    // 移除所有按钮的active类（包括桌面端）
                    categoryButtons.forEach(btn => btn.classList.remove('active'));
                    mobileCategoryButtons.forEach(btn => btn.classList.remove('active'));

                    // 为当前点击的按钮添加active类
                    this.classList.add('active');

                    // 同步到桌面端按钮
                    const desktopButton = document.querySelector(`#category-buttons .category-btn[data-category="${this.getAttribute('data-category')}"]`);
                    if (desktopButton) {
                        desktopButton.classList.add('active');
                    }

                    // 更新当前类别
                    currentCategory = this.getAttribute('data-category');

                    // 重置显示数量并筛选加载作品
                    resetDisplayedCount();
                    filterAndLoadWorks();
                });
            });
            
            // 滚动事件
            window.addEventListener('scroll', optimizedHandleScroll);
            
            // 窗口大小改变
            window.addEventListener('resize', handleResize);
            
            // 模态框内的事件监听器
            document.addEventListener('click', function(e) {
                // 标签页切换
                if (e.target.classList.contains('tab-button')) {
                    const tab = e.target.getAttribute('data-tab');
                    document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
                    document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
                    e.target.classList.add('active');
                    document.getElementById(`${tab}-tab`).classList.add('active');
                }
            });
            
            // 滑块值更新
            const batchSizeSlider = document.getElementById('batch-size');
            const batchSizeValue = document.getElementById('batch-size-value');
            if (batchSizeSlider) {
                batchSizeSlider.addEventListener('input', function() {
                    batchSizeValue.textContent = this.value;
                });
            }
            
            // 图片编辑按钮
            const editImageBtn = document.getElementById('edit-image-btn');
            if (editImageBtn) {
                editImageBtn.addEventListener('click', editImage);
            }
            
            // 轮播控制按钮
            const prevBtn = document.getElementById('prev-btn');
            const nextBtn = document.getElementById('next-btn');
            if (prevBtn) prevBtn.addEventListener('click', showPrevSlide);
            if (nextBtn) nextBtn.addEventListener('click', showNextSlide);

            // 下载图片按钮
            const downloadAiImageBtn = document.getElementById('download-ai-image');
            if (downloadAiImageBtn) {
                downloadAiImageBtn.addEventListener('click', downloadCurrentAiImage);
            }

            // 缩略图压缩按钮
            const thumbnailCompressBtn = document.getElementById('thumbnail-compress-btn');
            if (thumbnailCompressBtn) {
                thumbnailCompressBtn.addEventListener('click', compressThumbnails);
            }
        }

        // 重新扫描目录并更新作品数据
        function rescanAndUpdateWork(currentWork, currentImagePath) {
            try {
                // 从图片路径中提取目录信息
                const imagePathParts = currentImagePath.split('/');
                const imageName = imagePathParts.pop(); // 移除文件名
                const directoryPath = imagePathParts.join('/'); // 获取目录路径

                // 获取目录中的所有图片文件
                const allImageFiles = [];
                const imageExtensions = ['webp', 'jpg', 'png', 'jpeg'];

                // 这里应该调用后端API来获取最新的文件列表
                // 但为了保持简单，我们先使用现有逻辑
                if (currentWork.category === '根目录') {
                    // 根目录的处理
                    currentWork.aiImages.forEach(aiImage => {
                        const aiImagePath = currentImagePath.replace(/[^\/]+$/, aiImage);
                        allImageFiles.push(aiImage);
                    });
                } else {
                    // 子目录的处理
                    currentWork.aiImages.forEach(aiImage => {
                        const aiImagePath = currentImagePath.replace(/[^\/]+$/, aiImage);
                        allImageFiles.push(aiImagePath);
                    });
                }

                console.log('重新扫描找到的AI生成图:', allImageFiles);

            } catch (error) {
                console.error('重新扫描目录时出错:', error);
            }
        }

        // 缩略图压缩功能
        function compressThumbnails() {
            const btn = document.getElementById('thumbnail-compress-btn');
            const originalContent = btn.innerHTML;

            // 显示加载状态
            btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>压缩中...';
            btn.disabled = true;

            // 显示处理中提醒
            showAlert('正在压缩图片，生成 400x400 jpg 格式的缩略图...', 'info');

            // 发送压缩请求
            fetch('/api.php?api_id=thumbnail_compress', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    tempPath: <?php echo json_encode($tempPath); ?>,
                    exludedFolders: <?php echo json_encode($excludedFolders); ?>
                })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                // 恢复按钮状态
                btn.innerHTML = originalContent;
                btn.disabled = false;

                if (data.success) {
                    showAlert(`压缩完成！成功压缩 ${data.compressed_count} 张图片`, 'success');

                    // 如果有失败的图片，显示警告信息
                    if (data.failed_count > 0) {
                        showAlert(`有 ${data.failed_count} 张图片压缩失败`, 'warning');
                    }

                    // 重新扫描并更新作品数据，显示新生成的缩略图
                    setTimeout(() => {
                        // 重新初始化应用，重新扫描目录并更新作品数据
                        initApp();
                        console.log('作品数据已重新加载');
                    }, 1000);
                } else {
                    showAlert('压缩失败: ' + data.message, 'error');
                }
            })
            .catch(error => {
                console.error('压缩请求错误:', error);

                // 恢复按钮状态
                btn.innerHTML = originalContent;
                btn.disabled = false;

                showAlert('压缩请求失败: ' + error.message, 'error');
            });
        }

        // 显示动态提醒
        function showAlert(message, type = 'info') {
            const alertContainer = document.getElementById('edit-alert');
            alertContainer.className = 'alert alert-' + type;
            alertContainer.textContent = message;
            alertContainer.classList.remove('hidden');

            // 3秒后自动隐藏
            setTimeout(() => {
                alertContainer.classList.add('hidden');
            }, 3000);
        }

        // 图片编辑功能
        function editImage() {
            const prompt = document.getElementById('prompt').value;
            const batchSize = document.getElementById('batch-size').value;
            const resolution = document.getElementById('resolution').value;
            const currentImage = document.getElementById('current-image').value;
            
            // 验证输入
            if (!prompt.trim()) {
                showAlert('请输入Prompt', 'error');
                return;
            }
            
            if (!currentImage) {
                showAlert('未选择图片', 'error');
                return;
            }
            
            // 显示加载状态
            const editLoading = document.getElementById('edit-loading');
            const editBtn = document.getElementById('edit-image-btn');
            editLoading.classList.remove('hidden');
            editBtn.disabled = true;
            
            // 显示处理中提醒
            showAlert('正在处理图片生成请求...', 'info');
            
            // 构造API请求数据
            const requestData = {
                prompt: prompt,
                image: currentImage,
                batch_size: parseInt(batchSize),
                resolution: resolution
            };
            
            console.log('发送API请求:', requestData);
            
            // 发送请求到API - 使用绝对路径避免路径问题
            fetch('/api.php?api_id=38502', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            })
            .then(response => {
                console.log('API响应状态:', response.status);

                // 检查响应状态
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态: ${response.status}`);
                }

                return response.json();
            })
            .then(data => {
                console.log('API响应数据:', data);
                
                // 隐藏加载状态
                editLoading.classList.add('hidden');
                editBtn.disabled = false;
                
                // 显示API响应信息
                const apiResponseElement = document.getElementById('api-response');
                apiResponseElement.innerHTML = '<pre>' + JSON.stringify(data, null, 2) + '</pre>';
                
                if (data.success) {
                    showAlert('图片生成成功！' + data.message, 'success');

                    // 获取当前作品
                    const currentWork = worksData.find(work => work.originalImage === currentImage);
                    if (currentWork) {
                        // 重新扫描目录以获取最新的AI生成图
                        rescanAndUpdateWork(currentWork, currentImage);

                        // 如果API返回了新图片信息，也更新到作品中
                        if (data.downloaded_images && data.downloaded_images.length > 0) {
                            const newAiImages = data.downloaded_images.map(img => img.filename);

                            // 避免重复添加
                            newAiImages.forEach(newImg => {
                                if (!currentWork.aiImages.includes(newImg)) {
                                    currentWork.aiImages.push(newImg);
                                }
                            });
                        }

                        // 刷新轮播显示
                        initCarousel(currentWork);

                        // 刷新页面上的作品网格以显示新的缩略图
                        filterAndLoadWorks();
                    }
                } else {
                    showAlert('图片生成失败: ' + data.message, 'error');
                }
            })
            .catch(error => {
                console.error('API请求错误:', error);
                
                // 隐藏加载状态
                editLoading.classList.add('hidden');
                editBtn.disabled = false;
                
                // 更详细的错误信息
                let errorMessage = '图片生成请求失败: ';
                if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {
                    errorMessage += '网络连接失败，请检查API服务器是否正常运行';
                } else {
                    errorMessage += error.message;
                }
                
                showAlert(errorMessage, 'error');

                // 显示错误信息
                const apiResponseElement = document.getElementById('api-response');
                apiResponseElement.innerHTML = '<pre>网络错误详情: ' + error.message + '\n错误类型: ' + error.name + '</pre>';
            });
        }

        // 下载当前AI生成图片
        function downloadCurrentAiImage() {
            if (carouselSlides.length === 0 || currentSlideIndex >= carouselSlides.length) {
                showAlert('没有可下载的图片', 'error');
                return;
            }

            const currentSlide = carouselSlides[currentSlideIndex];
            const imgElement = currentSlide.querySelector('img');

            if (!imgElement || !imgElement.src) {
                showAlert('无法获取图片信息', 'error');
                return;
            }

            const imageUrl = imgElement.src;

            // 在新窗口打开图片URL
            window.open(imageUrl, '_blank');

            // 创建下载链接
            const link = document.createElement('a');
            link.href = imageUrl;

            // 从URL中提取文件名
            const urlParts = imageUrl.split('/');
            let fileName = urlParts[urlParts.length - 1];

            // 移除时间戳参数（如果有）
            fileName = fileName.split('?')[0];

            link.download = fileName;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            showAlert('图片下载成功！', 'success');
        }

        // 处理键盘导航
        function handleKeyboardNavigation(e) {
            if (e.key === 'Escape' && !modal.classList.contains('hidden')) {
                closeModal();
            } else if (e.key === 'ArrowDown' || e.key === 'ArrowRight') {
                window.scrollBy({ top: 300, behavior: 'smooth' });
            } else if (e.key === 'ArrowUp' || e.key === 'ArrowLeft') {
                window.scrollBy({ top: -300, behavior: 'smooth' });
            } else if (e.key === 'ArrowLeft' && !modal.classList.contains('hidden')) {
                showPrevSlide();
            } else if (e.key === 'ArrowRight' && !modal.classList.contains('hidden')) {
                showNextSlide();
            }
        }

        // 切换暗色模式
        function toggleDarkMode() {
            isDarkMode = !isDarkMode;
            if (isDarkMode) {
                document.body.classList.remove('light-mode');
                document.body.classList.add('dark-mode');
                themeToggle.innerHTML = '<i class="fas fa-sun"></i>';
            } else {
                document.body.classList.remove('dark-mode');
                document.body.classList.add('light-mode');
                themeToggle.innerHTML = '<i class="fas fa-moon"></i>';
            }
        }

        // 切换移动端菜单
        function toggleMobileMenu() {
            mobileMenu.classList.toggle('hidden');
        }

        // 处理滚动
        function handleScroll() {
            // 隐藏滚动指示器
            if (window.scrollY > 200) {
                scrollIndicator.classList.add('hidden');
            }
            
            // 无限滚动 - 当接近页面底部时自动加载更多
            if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 500 && !isLoading && loadMoreBtn && loadMoreBtn.classList.contains('hidden') === false) {
                loadMoreWorks();
            }
        }

        // 处理窗口大小改变
        function handleResize() {
            if (window.innerWidth >= 768) {
                mobileMenu.classList.add('hidden');
            }
        }

        // 显示滚动指示器
        function showScrollIndicator() {
            setTimeout(() => {
                if (window.scrollY < 200) {
                    scrollIndicator.classList.remove('hidden');
                }
            }, 2000);
        }

        // 重置显示数量
        function resetDisplayedCount() {
            displayedCount = 8;
            galleryGrid.innerHTML = '<div class="col-span-full text-center py-12"><div class="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-indigo-600"></div><p class="mt-4 text-gray-600 dark:text-gray-400">正在加载产品图...</p></div>';
        }

        // 筛选并加载作品
        function filterAndLoadWorks() {
            // 获取筛选后的作品
            let filteredWorks = [];
            
            if (currentCategory === '根目录') {
                filteredWorks = worksData.filter(work => work.category === '根目录');
            } else {
                filteredWorks = worksData.filter(work => work.category === currentCategory);
            }
            
            // 按创建时间排序（最新在前）
            filteredWorks.sort((a, b) => new Date(b.created) - new Date(a.created));
            
            // 只显示指定数量的作品
            const limitedWorks = filteredWorks.slice(0, displayedCount);
            
            // 渲染作品
            setTimeout(() => {
                renderWorks(limitedWorks);

                // 为新渲染的作品卡片添加点击事件
                addCardClickEvents();

                // 更新加载更多按钮状态
                if (filteredWorks.length <= displayedCount) {
                    if (loadMoreBtn) loadMoreBtn.classList.add('hidden');
                } else {
                    if (loadMoreBtn) loadMoreBtn.classList.remove('hidden');
                }
            }, 500);
        }

        // 防抖函数
        function debounce(func, wait) {
            let timeout;
            return function executedFunction(...args) {
                const later = () => {
                    clearTimeout(timeout);
                    func(...args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        }
        
        // 节流函数
        function throttle(func, limit) {
            let inThrottle;
            return function() {
                const args = arguments;
                const context = this;
                if (!inThrottle) {
                    func.apply(context, args);
                    inThrottle = true;
                    setTimeout(() => inThrottle = false, limit);
                }
            };
        }
        
        // 图片懒加载
        function lazyLoadImages() {
            const imageObserver = new IntersectionObserver((entries, observer) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const img = entry.target;
                        img.src = img.dataset.src;
                        img.classList.remove('lazy');
                        img.classList.add('loaded');
                        observer.unobserve(img);
                    }
                });
            }, {
                rootMargin: '50px' // 提前50px开始加载
            });
            
            document.querySelectorAll('img.lazy').forEach(img => {
                imageObserver.observe(img);
            });
        }
        
        // 优化渲染作品函数
        function renderWorks(works) {
            galleryGrid.innerHTML = '';
            
            if (works.length === 0) {
                galleryGrid.innerHTML = `
                    <div class="col-span-full text-center py-16">
                        <div class="inline-block p-6 bg-gray-100 dark:bg-gray-800 rounded-2xl mb-6">
                            <i class="fas fa-search text-6xl text-gray-400"></i>
                        </div>
                        <h3 class="text-2xl font-bold text-gray-700 dark:text-gray-300 mb-2">未找到产品图</h3>
                        <p class="text-gray-500 dark:text-gray-400">请尝试其他分类或上传新产品</p>
                    </div>
                `;
                return;
            }
            
            // 使用文档片段提高性能
            const fragment = document.createDocumentFragment();
            
            works.forEach(work => {
                const workCard = document.createElement('div');
                workCard.className = 'card group animate-fade-in-up';
                workCard.innerHTML = `
                    <div class="thumbnail-container">
                        <img src="${work.thumbnail}" alt="${work.imageName}" class="thumbnail">
                        <div class="category-tag">${work.category}</div>
                    </div>
                    <div class="card-content">
                        <h3 class="card-title">${work.imageName}</h3>
                        <div class="card-meta">
                            <span class="date">${work.created}</span>
                            <span class="models">
                                <i class="fas fa-image text-xs mr-1"></i>
                                产品图
                            </span>
                        </div>
                    </div>
                `;

                // 添加卡片点击事件
                workCard.addEventListener('click', function() {
                    openModal(work);
                });

                // 为图片添加独立的点击事件
                const thumbnail = workCard.querySelector('.thumbnail');
                if (thumbnail) {
                    thumbnail.addEventListener('click', function(e) {
                        e.stopPropagation(); // 防止事件冒泡到card
                        openModal(work);
                    });
                }

                fragment.appendChild(workCard);
            });
            
            galleryGrid.appendChild(fragment);
            
            // 初始化图片懒加载
            setTimeout(lazyLoadImages, 100);
        }
        
        // 优化加载更多功能
        const loadMoreWorks = debounce(function() {
            if (isLoading) return;
            
            isLoading = true;
            if (loadMoreBtn) {
                loadMoreBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i><span>加载中...</span>';
            }
            
            // 模拟加载延迟
            setTimeout(() => {
                displayedCount += 8;
                filterAndLoadWorks();
                isLoading = false;
                if (loadMoreBtn) {
                    loadMoreBtn.innerHTML = '<span>加载更多产品图</span>';
                }
            }, 300); // 减少延迟时间
        }, 300);
        
        // 优化滚动处理
        const optimizedHandleScroll = throttle(function() {
            // 隐藏滚动指示器
            if (window.scrollY > 200) {
                scrollIndicator.classList.add('hidden');
            }
            
            // 无限滚动 - 当接近页面底部时自动加载更多
            if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 1000 && !isLoading && loadMoreBtn && loadMoreBtn.classList.contains('hidden') === false) {
                loadMoreWorks();
            }
        }, 200); // 节流200ms

        // 初始化轮播
        function initCarousel(work) {
            const carousel = document.getElementById('ai-carousel');
            const indicatorsContainer = document.getElementById('carousel-indicators');

            // 检查必要元素是否存在
            if (!carousel || !indicatorsContainer) {
                console.warn('轮播元素未找到');
                return;
            }

            // 清空现有内容
            // 保留控制按钮和指示器容器
            const controls = carousel.querySelector('.carousel-controls');
            const indicators = carousel.querySelector('.carousel-indicators');

            // 清空轮播项
            const children = Array.from(carousel.children);
            for (const child of children) {
                if (child !== controls && child !== indicators) {
                    carousel.removeChild(child);
                }
            }

            // 重新添加控制按钮和指示器容器
            if (controls) carousel.appendChild(controls);
            if (indicators) carousel.appendChild(indicators);

            // 清空指示器
            indicatorsContainer.innerHTML = '';

            // 使用AI生成图的缩略图路径
            const aiThumbnails = work.aiThumbnails || work.aiImages;

            if (aiThumbnails && aiThumbnails.length > 0) {
                carouselSlides = [];
                currentSlideIndex = 0;

                // 对AI生成图按时间戳进行倒序排序（最新的在前）
                const sortedAiImages = [...aiThumbnails].sort((a, b) => {
                    // 从文件名中提取时间戳
                    const getTimestamp = (filename) => {
                        if (typeof filename === 'string') {
                            const parts = filename.split('_');
                            if (parts.length >= 3) {
                                // 时间戳是倒数第二部分
                                return parts[parts.length - 2];
                            }
                        }
                        return 0; // 如果格式不符合，返回0
                    };

                    const timestampA = getTimestamp(a);
                    const timestampB = getTimestamp(b);

                    // 按时间戳倒序排序（最新的在前）
                    return timestampB.localeCompare(timestampA);
                });

                sortedAiImages.forEach((aiImage, index) => {
                    // 构建正确的图片路径
                    let imgPath;
                    let originalPath;

                    try {
                        // 获取原始AI生成图的路径（用于点击放大）
                        if (work.category === '根目录') {
                            originalPath = work.originalImage;
                            originalPath = originalPath.replace(/[^\/]+$/, work.aiImages[index]);
                        } else {
                            // 对于子目录，需要构建正确的路径
                            const basePath = work.originalImage.substring(0, work.originalImage.lastIndexOf('/'));
                            originalPath = basePath + '/' + work.aiImages[index];
                        }

                        imgPath = aiImage; // 使用缩略图路径
                    } catch (error) {
                        console.error('构建图片路径时出错:', error);
                        return; // 跳过这个图片
                    }

                    // 创建轮播项
                    const slide = document.createElement('div');
                    slide.className = 'carousel-slide';
                    if (index === 0) {
                        slide.classList.add('active');
                    }

                    const img = document.createElement('img');
                    // 使用时间戳来避免缓存问题，确保显示最新的图片
                    img.src = imgPath + '?t=' + new Date().getTime();
                    img.alt = `AI生成图 ${index + 1}`;
                    img.className = 'w-full h-full object-contain';

                    // 添加点击事件，点击后放大显示原图
                    img.onclick = function() {
                        this.src = originalPath + '?t=' + new Date().getTime();
                    };

                    img.onload = function() {
                        console.log('AI生成图缩略图加载成功:', imgPath);
                    };
                    img.onerror = function() {
                        console.warn('AI生成图缩略图加载失败:', imgPath);
                        // 显示占位图或错误信息
                        this.src = '';
                        this.alt = `AI生成图 ${index + 1} (加载失败)`;
                    };

                    slide.appendChild(img);
                    carousel.insertBefore(slide, controls);
                    carouselSlides.push(slide);

                    // 创建指示器
                    const indicator = document.createElement('div');
                    indicator.className = 'indicator';
                    if (index === 0) {
                        indicator.classList.add('active');
                    }
                    indicator.addEventListener('click', () => showSlide(index));
                    indicatorsContainer.appendChild(indicator);
                });

                // 显示控制按钮和指示器
                if (controls) controls.style.display = 'flex';
                if (indicatorsContainer) indicatorsContainer.style.display = 'flex';

                // 显示AI生成图标签页
                const aiTab = document.querySelector('[data-tab="ai"]');
                if (aiTab) {
                    aiTab.style.display = 'block';
                }

            } else {
                // 没有AI生成图时显示提示
                const noImages = document.createElement('div');
                noImages.className = 'flex items-center justify-center h-full';
                noImages.innerHTML = '<p class="text-gray-500 text-center">暂无AI生成图<br>请使用右侧编辑工具生成</p>';
                carousel.insertBefore(noImages, controls);

                // 隐藏控制按钮
                if (controls) controls.style.display = 'none';
                if (indicatorsContainer) indicatorsContainer.style.display = 'none';

                // 隐藏AI生成图标签页
                const aiTab = document.querySelector('[data-tab="ai"]');
                if (aiTab) {
                    aiTab.style.display = 'none';
                }
            }
        }

        // 显示指定幻灯片
        function showSlide(index) {
            if (index < 0 || index >= carouselSlides.length) return;
            
            // 隐藏所有幻灯片
            carouselSlides.forEach(slide => slide.classList.remove('active'));
            
            // 显示指定幻灯片
            carouselSlides[index].classList.add('active');
            
            // 更新指示器
            const indicators = document.querySelectorAll('.indicator');
            indicators.forEach((indicator, i) => {
                if (i === index) {
                    indicator.classList.add('active');
                } else {
                    indicator.classList.remove('active');
                }
            });
            
            currentSlideIndex = index;
        }

        // 显示下一张幻灯片
        function showNextSlide() {
            const nextIndex = (currentSlideIndex + 1) % carouselSlides.length;
            showSlide(nextIndex);
        }

        // 显示上一张幻灯片
        function showPrevSlide() {
            const prevIndex = (currentSlideIndex - 1 + carouselSlides.length) % carouselSlides.length;
            showSlide(prevIndex);
        }

        // 打开模态框
        function openModal(work) {
            // 设置模态框内容
            document.getElementById('modal-title').textContent = work.imageName;
            document.getElementById('modal-image-name').textContent = work.imageName;
            document.getElementById('modal-category').textContent = work.category;
            document.getElementById('modal-created').textContent = work.created;

            // 设置原始图缩略图，先显示缩略图提高加载速度
            const originalImage = document.getElementById('original-image');

            // 设置缩略图作为默认显示
            originalImage.src = work.thumbnail || '';

            // 添加点击事件，点击后放大显示原图
            originalImage.onclick = function() {
                if (this.src !== (work.originalImage + '?t=' + new Date().getTime())) {
                    this.src = work.originalImage + '?t=' + new Date().getTime();
                }
            };

            document.getElementById('current-image').value = work.originalImage;

            // 异步初始化AI生成图轮播，避免阻塞UI
            setTimeout(() => {
                initCarousel(work);
            }, 200);

            // 重置标签页状态 - 默认显示原始图
            document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
            document.querySelector('[data-tab="original"]').classList.add('active');
            document.getElementById('original-tab').classList.add('active');

            // 清空API响应信息
            document.getElementById('api-response').innerHTML = '<pre>暂无API响应信息</pre>';

            // 隐藏提醒
            document.getElementById('edit-alert').classList.add('hidden');

            // 显示模态框
            modal.classList.remove('hidden');
            document.body.style.overflow = 'hidden';
        }

        // 关闭模态框
        function closeModal() {
            modal.classList.add('hidden');
            document.body.style.overflow = 'auto';
        }

        // 初始化应用
        document.addEventListener('DOMContentLoaded', initApp);
    </script>
</body>
</html>